package cn.iocoder.yudao.module.course.service.coursematerials;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.course.controller.admin.coursematerials.vo.*;
import cn.iocoder.yudao.module.course.dal.dataobject.coursematerials.CourseMaterialsDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.course.dal.mysql.coursematerials.CourseMaterialsMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.course.enums.ErrorCodeConstants.*;

/**
 * 课程素材 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class CourseMaterialsServiceImpl implements CourseMaterialsService {

    @Resource
    private CourseMaterialsMapper materialsMapper;

    @Override
    public Long createMaterials(CourseMaterialsSaveReqVO createReqVO) {
        // 插入
        CourseMaterialsDO materials = BeanUtils.toBean(createReqVO, CourseMaterialsDO.class);
        materialsMapper.insert(materials);
        // 返回
        return materials.getId();
    }

    @Override
    public void updateMaterials(CourseMaterialsSaveReqVO updateReqVO) {
        // 校验存在
        validateMaterialsExists(updateReqVO.getId());
        // 更新
        CourseMaterialsDO updateObj = BeanUtils.toBean(updateReqVO, CourseMaterialsDO.class);
        materialsMapper.updateById(updateObj);
    }

    @Override
    public void deleteMaterials(Long id) {
        // 校验存在
        validateMaterialsExists(id);
        // 删除
        materialsMapper.deleteById(id);
    }

    private void validateMaterialsExists(Long id) {
        if (materialsMapper.selectById(id) == null) {
            throw exception(COURSE_MATERIALS_NOT_EXISTS);
        }
    }

    @Override
    public CourseMaterialsDO getMaterials(Long id) {
        return materialsMapper.selectById(id);
    }

    @Override
    public PageResult<CourseMaterialsDO> getMaterialsPage(CourseMaterialsPageReqVO pageReqVO) {
        return materialsMapper.selectPage(pageReqVO);
    }

}